<?php

namespace App\Services\Pay;

use App\Models\Store;
use App\Models\StorePayWay;
use App\Models\UserRate;
use App\Services\AMQP\AMQPProduce;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class PayService
{

    public function closeOrder($outTradeNo,int $pay_status=3)
    {
        try {
            $dayOrderTable = 'orders_' . substr(preg_replace("/[a-zA-Z_]/", "", $outTradeNo), 0, 8);

            if($pay_status==3){
                $update = ['pay_status' => 3, 'pay_status_desc' => '支付失败', 'status' => 3];
            }else{
                $update = ['pay_status' => 6, 'pay_status_desc' => '已退款', 'status' => 3];
            }

            DB::table('orders')->where('out_trade_no', $outTradeNo)->update($update);
            if (DB::connection()->getSchemaBuilder()->hasTable($dayOrderTable)) {
                DB::table($dayOrderTable)->where('out_trade_no', $outTradeNo)->update($update);
            } else {
                error_log(date('Y-m-d H:i:s') . " 【关闭订单失败2】： " . json_encode([$dayOrderTable, $outTradeNo]) . "\n\n", 3, "/tmp/" . 'close-order' . date('Ymd') . ".log");
            }
        } catch (\Exception $exception) {
            error_log(date('Y-m-d H:i:s') . " 【关闭订单失败3】： " . json_encode([$exception->getMessage(), $outTradeNo]) . "\n\n", 3, "/tmp/" . 'close-order' . date('Ymd') . ".log");
        }
    }


    public static function payOkHandle(array $data): void
    {
        try {
            //记录日志文件
            $produce = new AMQPProduce();
            $produce->run($data, "pay", "dev");
        } catch (\Throwable $e) {
            //记录日志文件
            Log::channel('pay')->error("payOkHandle" . $e->getMessage() . $e->getFile() . $e->getLine(), $data);
        }
    }

    public static function refundOkHandle(array $data): void
    {
        try {
            //记录日志文件
            $produce = new AMQPProduce();
            $produce->run($data, "refund", "dev");
        } catch (\Throwable $e) {
            //记录日志文件
            Log::channel('refund')->error("refundOkHandle" . $e->getMessage() . $e->getFile() . $e->getLine(), $data);
            throw new \Exception($e->getMessage() . $e->getFile() . $e->getLine());
        }
    }

    public static function produceOrderOkHandle(array $data)
    {
        try {
            Log::channel('waitpay')->error("waitpay-start" . date("Y-m-d H:i:s", time()), $data);
//            $produce = new AMQPProduce();
//            $produce->run($data, "waitpay", "dev");
//            $data = [
//                "out_trade_no" => $out_trade_no,
//                "type" => $type
//            ];
//            if ($type == 2) {
//                $data["refund_no"] = $refund_no;
//            }
//            $redis = Redis::connection('amqpQueue');
//            $redis->rPush("payListener", json_encode($data));
//            Log::channel('amqp')->info("payListener:", $data);

//            $redis = Redis::connection('amqpQueue');

        } catch (\Exception $e) {
            Log::channel('waitpay')->error("waitpay-error" . $e->getMessage() . $e->getFile() . $e->getLine(), $data);
        }
    }

    public static function getCostRate(string $ways_type, int $user_id, $total_amount): float
    {
        $user_rate_obj = UserRate::where('ways_type', $ways_type)
            ->where('user_id', $user_id)
            ->where('status', 1)
            ->orderby('created_at', 'desc')
            ->first();
        $rate = $user_rate_obj->rate;
        if ($user_rate_obj->ways_source == "unionpay") {
            $rate = $user_rate_obj->rate_a;
            if ($total_amount > 1000) {
                $rate = $user_rate_obj->rate_c;
            }
        }
        return $rate;
    }


    public static function getWayRate(string $ways_source, string $store_id, int $store_pid, float $total_amount): array
    {
        $ways = StorePayWay::where('ways_source', $ways_source)
            ->where('store_id', $store_id)
            ->where('status', 1)
            ->orderBy('sort', 'asc')
            ->first();
        if (!$ways) {
            $store_id = "";
            $srore_id_pid = Store::where('id', $store_pid)
                ->select('store_id')
                ->first();
            if ($srore_id_pid) {
                $store_id = $srore_id_pid->store_id;
            }
            $ways = StorePayWay::where('ways_source', $ways_source)
                ->where('store_id', $store_id)
                ->where('status', 1)
                ->orderBy('sort', 'asc')
                ->first();
        }
        $rate = $ways->rate;
        if ($ways_source == "unionpay") {
            $rate = $ways->rate_a;
            if ($total_amount > 1000) {
                $rate = $ways->rate_c;
            }
        }
        return [(float)$rate, $ways->ways_type];
    }


    //云闪付费率分析 并且获取
    public static function getYSFCostRate($user_rate_obj, $total_amount): float
    {
        $rate = $user_rate_obj ? $user_rate_obj->rate_a : 0;
        if ($total_amount > 1000) {
            $rate = $user_rate_obj ? $user_rate_obj->rate_c : 0;
        }
//        "rate_change" => [
//        1 => $userrate[$userNode["id"]]["rate_a"], //(0-1000】
//        2 => $userrate[$userNode["id"]]["rate_c"]// >1000以上
//    ],//浮动费率配置
//      "debit_max_fee_amount" => $userrate[$userNode["id"]]["store_all_rate_b_top"] //借记卡封顶费率  最大金额
        return $rate;
    }

    public static function getYSFWayRate($ways, $total_amount): float
    {
        $rate = $ways ? $ways->rate_a : 0;
        if ($total_amount > 1000) {
            $rate = $ways ? $ways->rate_c : 0;
        }
        return $rate;
    }

}